package com.collections;

public class CompactHashMap {

    static class Entry {

		int hash;
		final int key;
		int value;
        Entry next;

		public Entry(int hash, int key, int value, Entry next) {
			this.hash = hash;
			this.key = key;
			this.value = value;
			this.next = next;
		}

		public final int getKey() {
            return key;
        }

        public final int getValue() {
            return value;
        }

        public final int setValue(int newValue) {
            int oldValue = value;
            value = newValue;
            return oldValue;
        }
	}
    static final int DEFAULT_INITIAL_CAPACITY = 16;
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    static int indexFor(int h, int length) {
        return (h & (length-1));
    }
    private final float loadFactor;
    private int threshold;
    
    public int getSize() {
		return size;
	}
    
	private Entry[] table;

    private int size;
    
    public CompactHashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }
    
	public CompactHashMap(int initialCapacity){
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
	
    public CompactHashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        this.loadFactor = loadFactor;
        threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];

    }

    void addEntry(int hash, int key, int value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = hash(key);
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }
    
    
	public boolean containsKey(int key) {
        int hash = hash(key);
        for (Entry e = table[indexFor(hash, table.length)]; null != e; e = e.next) {
            if (e.hash == hash &&
                (e.key == key))
                return true;
        }
        return false;
    }
    
    
    public boolean containsValue(int value) {
        for (Entry bucketHead : table)
            for (Entry e = bucketHead ; e != null ; e = e.next)
                if (value == e.value)
                    return true;
        return false;
    }
    
    void createEntry(int hash, int key, int value, int bucketIndex) {
    	Entry e = table[bucketIndex];
    	table[bucketIndex] = new Entry(hash, key, value, e);
    	size++;
    }
    
    public int get(int key) {
        Entry entry = getEntry(key);

        return null == entry ? Integer.MIN_VALUE : entry.getValue();
    }
    
    final int hash(int k) {
        int h = 0;
        h ^= k;
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
    
    public void put(int key, int value) {
		int hash = hash(key);
		int i = indexFor(hash, table.length);	
        for (Entry e = table[i]; e != null; e = e.next) {
            int k;
            if (e.hash == hash && ((k = e.key) == key || key == k )) {
                e.value = value;
                return;
            }
        }
        addEntry(hash, key, value, i);
	}
    
    final Entry getEntry(int key) {
        int hash = hash(key);
        for (Entry e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            if (e.hash == hash && e.key == key)
                return e;
        }
        return null;
    }
    
    public int remove(int key) {
        Entry e = removeEntryForKey(key);
        return (e == null ? Integer.MIN_VALUE : e.value);
    }

	void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        transfer(newTable);
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }
    
    final Entry removeEntryForKey(int key) {
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        Entry prev = table[i];
        Entry e = prev;

        while (e != null) {
            Entry next = e.next;
            if (e.hash == hash && e.key == key) {
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }
    
    public String toString() {
    	if ( size == 0 )
            return "{}";
        
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        int counter = 0;
        for (Entry bucketHead : table) {
        	
        	for (Entry e = bucketHead; e!=null; e=e.next){
	            int key = e.getKey();
	            int value = e.getValue();
	            sb.append(key);
	            sb.append('=');
	            sb.append(value);
	            if ( counter < size-1)
	            	sb.append(',').append(' ');
	            counter++;
        	}
        }
		return sb.append('}').toString();
    }
    
    
	void transfer(Entry[] newTable) {
        int newCapacity = newTable.length;
        for (Entry e : table) {
            while(null != e) {
                Entry next = e.next;

                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }
}
